import requests
from logger import logger


class CheckCookies:

    @staticmethod
    def zhihu_check_cookies(cookies):
        """请求知乎个人信息接口，判断cookies是否生效"""
        # 个人信息接口
        url = 'https://www.zhihu.com/api/v4/me?include=ad_type%2Cavailable_message_types%2Cdefault_notifications_count%2Cfollow_notifications_count%2Cvote_thank_notifications_count%2Cmessages_count%2Cdraft_count%2Cemail%2Caccount_status%2Cis_bind_phone%2Cfollowing_question_count%2Cis_force_renamed%2Crenamed_fullname'
        headers = {
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36',
        }
        s = requests.session()
        for cookie in cookies:
            s.cookies.set(cookie['name'], cookie['value'])

        r = s.get(url, headers=headers)
        # 个人信息接口，可以查到name，cookies依旧生效
        error = r.json().get('error')
        if error:
            message = error.get('message')
            logger.warning(f'知乎cookies检测失败, message: {message}')
            return False
        else:
            return True
